﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Data;
using System.Net;
using System.Configuration;
using System.Xml;
using System.Xml.Linq;

namespace Ogdi.InteractiveSdk.WebForms.Forms
{
    public partial class DataCatalogForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    //  Dynmaically populate containerDropdown
                    var containers = new List<String>();
                    // 1000 is the max results Azure Table Storage allows per query
                    var containerResult = ServiceInterface.GetData("", "AvailableEndpoints", 1000);
                    var containerData = containerResult.Xml;

                    foreach (var element in containerData.Elements("properties"))
                    {
                        string description = element.Element("description").Value;
                        string alias = element.Element("alias").Value;

                        containerDropdown.Items.Add
                        (
                            new ListItem(description, alias)
                        );
                    }
                    PopulateCategoriesList();
                    SetLegalDisclaimer();
                }
                catch (Exception exception)
                {
                    ShowError(exception.Message);
                }

                //  Fill with all data sets by default
                Fill();
            }
        }

        private void SetLegalDisclaimer()
        {
            var firstCategory = containerDropdown.SelectedValue;
            var filter = "alias eq '" + firstCategory + "'";
            // 1000 is the max results Azure Table Storage allows per query
            var containerResult = ServiceInterface.GetData("", "AvailableEndpoints", filter, 1000, null, null);
            var containerData = containerResult.Xml;

            var disclaimer = containerData.Elements("properties").First().Element("disclaimer");

            if (disclaimer != null)
            {
                legalDisclaimerLink.Visible = true;
                legalDisclaimer.InnerText = disclaimer.Value;
            }
            else
            {
                legalDisclaimerLink.Visible = false;
            }
        }

        private void PopulateCategoriesList()
        {
            //  Dynmaically populate categories list
            List<String> categories = new List<String>();
            var container = containerDropdown.SelectedValue;
            // 1000 is the max results Azure Table Storage allows per query
            var result = ServiceInterface.GetData(container, "TableMetadata", 1000);
            var data = result.Xml;

            foreach (var element in data.Elements("properties"))
            {
                string category = element.Element("category").Value;
                if (!categories.Contains(category))
                {
                    categories.Add(category);
                }
            }
            categories.Sort();
            this.categoriesList.DataSource = categories;
            this.categoriesList.DataBind();
        }

        protected void categoryButton_Click(object sender, EventArgs e)
        {
            LinkButton linkButton = sender as LinkButton;
            string categoryName = linkButton.Text;

            // Clear all other link buttons to have deselected css class
            this.allCategoriesButton.CssClass = "linkNormal";
            foreach (DataListItem item in categoriesList.Items)
            {
                LinkButton lb = item.FindControl("categoryLink") as LinkButton;
                if (lb != null)
                    lb.CssClass = "linkNormal";
            }

            // Set the css class for this button
            linkButton.CssClass = "linkActive";

            string query = "category eq '" + categoryName + "'";
            Fill(categoryName, query);
        }

        protected void allCategoriesButton_Click(object sender, EventArgs e)
        {
            // Clear all other link buttons to have deselected css class
            foreach (DataListItem item in categoriesList.Items)
            {
                LinkButton lb = item.FindControl("categoryLink") as LinkButton;
                if (lb != null)
                    lb.CssClass = "linkNormal";
            }

            // Set the css class for this button
            this.allCategoriesButton.CssClass = "linkActive";

            Fill();
        }

        protected void Fill(string categoryName, string filter)
        {
            categoryLabel.Text = categoryName;

            try
            {
                //  Get catalog metadata
                var container = containerDropdown.SelectedValue;
                var result = ServiceInterface.GetData(container, "TableMetadata", filter, 1000, null, null);
                var data = result.Xml;

                //Old Code
                //xmlDataSource.Data = data.ToString();
                //this.dataSetsGrid.DataSource = xmlDataSource;
                //this.dataSetsGrid.DataBind();
                //this.dataSetsGrid.Visible = true;

                //Section 508 - Code which creates table data dynamically
                XmlDocument inputDoc = new XmlDocument();
                inputDoc.LoadXml(data.ToString());
                XmlNodeList propNodeList = inputDoc.GetElementsByTagName("properties");

                for (int i = 0; i < propNodeList.Count; i++)
                {
                    TableRow tblRow = new TableRow();

                    TableCell tblHeaderCell = new TableCell();
                    tblHeaderCell.Style.Add("text-align", "left");
                    tblHeaderCell.Attributes.Add("id", propNodeList[i].SelectSingleNode("entityset").InnerText);
                    tblHeaderCell.Text = "<a href=\"DataBrowser.aspx?Container=" + container + "&amp;EntitySet=" + propNodeList[i].SelectSingleNode("entityset").InnerText + "\">" + propNodeList[i].SelectSingleNode("name").InnerText + "</a>";

                    TableCell tblSourceCell = new TableCell();
                    tblSourceCell.Attributes.Add("headers", "hdrSource");
                    tblSourceCell.Text = propNodeList[i].SelectSingleNode("source").InnerText;

                    TableCell tblDescCell = new TableCell();
                    tblDescCell.Attributes.Add("headers", "hdrDescription");
                    tblDescCell.Text = propNodeList[i].SelectSingleNode("description").InnerText + "<br/><a href=\""
                        + propNodeList[i].SelectSingleNode("metadataurl").InnerText
                        + "\" target=\"_blank\">" + "More Information</a> "
                        + "<img alt=\"External Link for more information\" src=\"images/ExternalLink.png\" longdesc=\"desc/ExternalLink.txt\"/>";

                    tblRow.Cells.Add(tblHeaderCell);
                    tblRow.Cells.Add(tblSourceCell);
                    tblRow.Cells.Add(tblDescCell);

                    if (i % 2 == 0)
                    {
                        tblRow.Attributes.Add("style", "border:1 solid #F0F0F0 ; background-color:#FEFEFE");
                    }
                    else
                    {
                        tblRow.Attributes.Add("style", "border:1 solid #F0F0F0 ; background-color:#F4F4F4");
                    }

                    tblDataCatalog.Rows.Add(tblRow);
                }
                //end

                HideError();
            }
            catch (WebException webException)
            {
                ShowError(webException.Message);
            }
        }

        protected void Fill()
        {
            Fill("All Available Data Sets", null);
        }

        protected void ShowError(string message, string detail)
        {
            errorLabel.Text = message;
            errorDetailsLabel.Text = detail;
            errorPanel.Visible = true;

            //Old Code
            //dataSetsGrid.Visible = false;

            //Section 508 - Hiding the table
            tblDataCatalog.Visible = false;

        }

        protected void ShowError(string detail)
        {
            ShowError("Your request could not be completed. Please try again.", detail);
        }

        protected void HideError()
        {
            errorPanel.Visible = false;

            //Old Code
            //dataSetsGrid.Visible = true;

            //Section 508 - Showing the table
            tblDataCatalog.Visible = true;
        }

        protected void containerDropdown_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulateCategoriesList();
            SetLegalDisclaimer();
            Fill();
        }
    }
}
